package com.lh_travel.lohas.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.PointF;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseViewHolder;
import com.lh_travel.lohas.R;
import com.lh_travel.lohas.adapter.CommonAdapter;
import com.lh_travel.lohas.adapter.DoubleViewRecylerAdapter;
import com.lh_travel.lohas.adapter.ViewHolder;
import com.lh_travel.lohas.base.BaseFragment;
import com.lh_travel.lohas.base.api;
import com.lh_travel.lohas.domain.City;
import com.lh_travel.lohas.domain.DafultMessageEvent;
import com.lh_travel.lohas.domain.MutilBean;
import com.lh_travel.lohas.domain.ShotCut;
import com.lh_travel.lohas.widget.HeadGridView;
import com.lh_travel.lohas.widget.ScrollExpendListview;
import com.lh_travel.lohas.widget.SmoothScrollLayoutManger;
import com.tamic.novate.Throwable;
import com.tamic.novate.callback.RxResultCallback;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;

import rx.Subscription;
import rx.subscriptions.Subscriptions;

/**
 * Created by aaron on 2018/6/7.
 */

@SuppressLint("ValidFragment")
public class ChCityFragment extends BaseFragment {

    private boolean cn;

    private String selectedItems = "";
    private String selectedCity;
    private PictureAdapter pictureAdapter;
    private LayoutInflater mInflater;
    private View view;
    private HeadGridView gridview;
    private ArrayList<City.hotcity> hot;
    private ArrayList<City.citys> citylist;
    private ListView lv_shot_cut;
    private int postion = 0;
    private ArrayList<ShotCut> shotCuts = new ArrayList<>();
    private SwipeMenuRecyclerView rcy;
    private DoubleViewRecylerAdapter doubleadapter;
    private int mToPosition;
    private boolean mShouldScroll;
    private SmoothScrollLayoutManger layoutManager;
    private LinearLayout ll_bg;
    private RelativeLayout rl_content;

    public ChCityFragment(boolean cn) {
        this.cn = cn;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_search_content;
    }

    @Override
    protected void initView() {
        findviews();

    }

    @Override
    protected void initData() {

        if (cn) {

            new api(context).getCityList(cn ? "cn" : "foreign", new RxResultCallback<City>() {
                @Override
                public void onNext(Object tag, int code, String message, City response) {
                    hot = response.hot;
                    citylist = response.city_list;

                    setHotCity();
                }

                @Override
                public void onError(Object tag, Throwable e) {

                }

                @Override
                public void onCancel(Object tag, Throwable e) {

                }
            });

        }

    }

    private void findviews() {

        lv_shot_cut = findView(R.id.lv_shot_cut);
        rcy = findView(R.id.rcy);

        ll_bg = findView(R.id.ll_bg);
        rl_content = findView(R.id.rl_content);

        if (cn) {
            ll_bg.setVisibility(View.GONE);
            rl_content.setVisibility(View.VISIBLE);

        } else {

            ll_bg.setVisibility(View.VISIBLE);
            rl_content.setVisibility(View.GONE);

        }
    }

    private void setHotCity() {

        pictureAdapter = new PictureAdapter(hot, context);

        mInflater = (LayoutInflater) getActivity().getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = mInflater.inflate(R.layout.grid_hot, null);

        gridview = view.findViewById(R.id.gridview);

        gridview.setAdapter(pictureAdapter);

        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                selectedItems = selectedItems.equals(position + "") ? "" : position + "";

                selectedCity = hot.get(position).name;

                pictureAdapter.notifyDataSetChanged();

                DafultMessageEvent event = new DafultMessageEvent();

                event.TAG = "ContentSearchActivity";
                event.belong = cn ? "cn" : "foreign";
                event.message = selectedCity;

                EventBus.getDefault().post(event);

                activity.finish();

            }
        });

        initxrv();
        initShotCut();
    }

    private void initxrv() {

        ArrayList<MutilBean> datalist = new ArrayList<>();

        HashMap<Integer, Integer> map = new HashMap<>();

        map.put(1, R.layout.item_city);
        map.put(2, R.layout.item_city_2);

        // 返回：滑过1px时经历的时间(ms)。
        layoutManager = new SmoothScrollLayoutManger(context);

        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rcy.setLayoutManager(layoutManager);

        for (int x = 0; x < citylist.size(); x++) {

            postion = postion + 1;

            City.citys citys = citylist.get(x);

            datalist.add(new MutilBean(citys.name, "0", 1));

            shotCuts.add(new ShotCut(citys.name, postion));

            for (int y = 0; y < citys.items.size(); y++) {

                City.hotcity hotcity = citys.items.get(y);

                datalist.add(new MutilBean(hotcity.name, hotcity.id, 2));

                postion = postion + 1;
            }
        }


        doubleadapter = new DoubleViewRecylerAdapter<MutilBean>(datalist, map) {

            @Override
            public void convertTo(BaseViewHolder baseViewHolder, final MutilBean item) {

                switch (baseViewHolder.getItemViewType()) {

                    case 1:

                        baseViewHolder.setText(R.id.tv_name, item.name);

                        break;

                    case 2:

                        baseViewHolder.setText(R.id.tv_name, item.name);

                        baseViewHolder.setOnClickListener(R.id.tv_name, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                DafultMessageEvent event = new DafultMessageEvent();

                                event.TAG = "ContentSearchActivity";
                                event.belong = cn ? "cn" : "foreign";
                                event.message = item.name;

                                EventBus.getDefault().post(event);

                                activity.finish();

                            }
                        });

                        break;

                }


            }
        };

        doubleadapter.addHeaderView(view);

        rcy.setAdapter(doubleadapter);

        rcy.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                if (mShouldScroll) {
                    mShouldScroll = false;
                    //获取要置顶的项在当前屏幕的位置，mIndex是记录的要置顶项在RecyclerView中的位置
                    int n = mToPosition - layoutManager.findFirstVisibleItemPosition();
                    if (0 <= n && n < rcy.getChildCount()) {
                        //获取要置顶的项顶部离RecyclerView顶部的距离
                        int top = rcy.getChildAt(n).getTop();
                        //最后的移动
                        rcy.scrollBy(0, top);
                    }
                }
            }
        });
    }

    private void initShotCut() {

        CommonAdapter adapter = new CommonAdapter<ShotCut>(context, shotCuts, R.layout.text) {
            @Override
            public void convert(ViewHolder helper, ShotCut item, int position) {

                helper.setText(R.id.text, item.title);

            }
        };

        lv_shot_cut.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                smoothMoveToPosition(rcy, shotCuts.get(position).position);
            }
        });

        lv_shot_cut.setAdapter(adapter);
    }


    /**
     * 滑动到指定位置
     *
     * @param mRecyclerView
     * @param position
     */
    private void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) {
        // 第一个可见位置
        int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
        // 最后一个可见位置
        int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1));

        if (position < firstItem) {

            mRecyclerView.scrollToPosition(position);
        } else if (position <= lastItem) {

            int top = mRecyclerView.getChildAt(position - firstItem).getTop();
            mRecyclerView.scrollBy(0, top);

        } else {

            //  mRecyclerView.smoothScrollToPosition(position);
            mRecyclerView.scrollToPosition(position);
            mToPosition = position;
            mShouldScroll = true;
        }
    }

    /**
     * 热门城市
     */
    public class PictureAdapter extends BaseAdapter {
        private Context mcontext;

        private ArrayList<City.hotcity> bean = new ArrayList<City.hotcity>();

        public PictureAdapter(ArrayList<City.hotcity> bean, Context context) {
            super();
            this.mcontext = context;
            this.bean = bean;
        }

        @Override
        public int getCount() {

            if (null != bean) {
                return bean.size();
            } else {
                return 0;
            }
        }

        @Override
        public Object getItem(int position) {

            return bean.get(position);
        }

        @Override
        public long getItemId(int position) {

            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            ViewHolder viewHolder = null;

            if (convertView == null) {

                viewHolder = new ViewHolder();
                // 获得容器
                convertView = LayoutInflater.from(mcontext).inflate(R.layout.item_hotcity, null);

                // 初始化组件
                viewHolder.btn = (TextView) convertView.findViewById(R.id.text);

                // 给converHolder附加一个对象
                convertView.setTag(viewHolder);
            } else {
                // 取得converHolder附加的对象
                viewHolder = (ViewHolder) convertView.getTag();
            }

            // 给组件设置资源
            viewHolder.btn.setText(bean.get(position).name);

            if (selectedItems.equals(position + "")) {

                viewHolder.btn.setSelected(true);
            } else {

                viewHolder.btn.setSelected(false);
            }

            return convertView;
        }

        class ViewHolder {
            public TextView btn;

        }
    }
}
